import Component from "../Component.js";


export default class Editor extends Component {
    constructor() {
        super();

        this.pageNo = 1;
        this.pageNum = 0;
        this.pageSize = 10;
    }

    update(data) {
        this.updatePopup = this.app.popup.create({ el: '.mapfile-popup-update' });
        this.popup.close();
        this.updatePopup.open();

        const code = this.utils.getLocalStorage('code');
        this.$$("#mapfile-update-name").val(data.name);

        this.$$("#mapfile-update-sign").empty();
        for (const key in code.Sign) {
            if (code.Sign.hasOwnProperty(key)) {
                const sign = code.Sign[key];
                const option = `<option value="${sign.key}">${sign.desc}</option>`;
                this.$$("#mapfile-update-sign").append(option);
            }
        }
        this.$$("#mapfile-update-sign").val(data.sign);

        this.$$("#mapfile-update-type").empty();
        for (const key in code.MapType) {
            if (code.MapType.hasOwnProperty(key)) {
                const sign = code.MapType[key];
                const option = `<option value="${sign.key}">${sign.desc}</option>`;
                this.$$("#mapfile-update-type").append(option);
            }
        }
        this.$$("#mapfile-update-type").val(data.type);

        this.$$("#mapfile-update-piece").empty();
        for (const desc of code.MapType2Assembly[data.type].desc) {
            const option = `<option value="${desc[0]}">${desc[1]}</option>`;
            this.$$("#mapfile-update-piece").append(option);
        }
        this.$$("#mapfile-update-piece").val(data.piece);

        // 当类型发生改变时，图件类型也要随之改变
        this.$$("#mapfile-update-type").on("change", async () => {
            const type = this.$$("#mapfile-update-type").val();
            this.$$("#mapfile-update-piece").empty();
            for (const key in code.MapType2Assembly) {
                if (type === key) {
                    if (code.MapType2Assembly.hasOwnProperty(key)) {
                        for (const desc of code.MapType2Assembly[key].desc) {
                            const option = `<option value="${desc[0]}">${desc[1]}</option>`;
                            this.$$("#mapfile-update-piece").append(option);
                        }
                    }
                }
            }
        })

        this.$$("#mapfile-update-version").empty();
        for (let i = 0; i < 12; i++) {
            const result = moment().subtract(i, "months").format('YYYY-MM');
            const option = `<option value="${result}">${result}</option>`;
            this.$$("#mapfile-update-version").append(option);
        }
        this.$$("#mapfile-update-version").val(data.major_ver);

        this.$$("#mapfile-popup-update-submit").on("click", async () => {
            const meta = {
                name: this.$$("#mapfile-update-name").val(),
                sign: this.$$("#mapfile-update-sign").val(),
                type: this.$$("#mapfile-update-type").val(),
                piece: this.$$("#mapfile-update-piece").val(),
                version: this.$$("#mapfile-update-version").val(),
                meta_id: data.meta_id
            };

            const resp = await this.api.updateMeta(meta);
            if (resp.code !== 0) {
                this.toast(resp.message);
                return
            }

            await this.getDataByPageNO();
            this.updatePopup.close();
            this.popup.open();
        })

        this.$$("#mapfile-popup-update-cancel").on("click", async () => {
            this.updatePopup.close();
            this.popup.open();
        })
    }

    search() {
        const code = this.utils.getLocalStorage('code');

        this.$$("#mapfile-sign").empty();
        this.$$("#mapfile-sign").append(`<option value="">全部</option>`);
        for (const key in code.Sign) {
            if (code.Sign.hasOwnProperty(key)) {
                const sign = code.Sign[key];
                const option = `<option value="${sign.key}">${sign.desc}</option>`;
                this.$$("#mapfile-sign").append(option);
            }
        }

        this.$$("#mapfile-type").empty();
        this.$$("#mapfile-type").append(`<option value="">全部</option>`);
        for (const key in code.MapType) {
            if (code.MapType.hasOwnProperty(key)) {
                const sign = code.MapType[key];
                const option = `<option value="${sign.key}">${sign.desc}</option>`;
                this.$$("#mapfile-type").append(option);
            }
        }

        this.$$("#mapfile-piece").empty();
        this.$$("#mapfile-piece").append(`<option value="">全部</option>`);
        for (const desc of code.MapType2Assembly.A.desc) {
            const option = `<option value="${desc[0]}">${desc[1]}</option>`;
            this.$$("#mapfile-piece").append(option);
        }

        // 当类型发生改变时，图件类型也要随之改变
        this.$$("#mapfile-type").on("change", async () => {
            const type = this.$$("#mapfile-type").val();
            this.$$("#mapfile-piece").empty();
            this.$$("#mapfile-piece").append(`<option value="">全部</option>`);
            for (const key in code.MapType2Assembly) {
                if (type === key) {
                    if (code.MapType2Assembly.hasOwnProperty(key)) {
                        for (const desc of code.MapType2Assembly[key].desc) {
                            const option = `<option value="${desc[0]}">${desc[1]}</option>`;
                            this.$$("#mapfile-piece").append(option);
                        }
                    }
                }
            }
        })

        this.$$("#mapfile-search").on("click", async () => {
            await this.getDataByPageNO();
        })
    }

    page() {
        this.$$("#mapfile-popup-prev").on("click", async () => {
            this.delay('prev', async () => {
                if (this.pageNo > 1 ) {
                    this.pageNo = this.pageNo - 1;
                }
                await this.getDataByPageNO();
            }, 300);
        })

        this.$$("#mapfile-popup-next").on("click", async () => {
            this.delay('prev', async () => {
                if (this.pageNo < this.pageNum) {
                    this.pageNo = this.pageNo + 1;
                }
                await this.getDataByPageNO();
            }, 300);
        })

        this.$$("#mapfile-popup-close").on("click", async () => {
            this.popup.close();
        })
    }

    async getDataByPageNO() {
        this.mine = this.utils.getLocalStorage("mine");
        const code = this.utils.getLocalStorage('code');
        const filter = {
            code: this.mine.code,
            name: this.$$("#mapfile-name").val(),
            sign: this.$$("#mapfile-sign").val(),
            type: this.$$("#mapfile-type").val(),
            piece: this.$$("#mapfile-piece").val(),
            no: this.pageNo,
            size: this.pageSize
        };
        const data = await this.api.getMeta(filter);
        const metas = data.data;
        this.pageNum = Math.ceil(metas.total / this.pageSize);
        this.$$("#mapfile-table-page").html(`总计: ${this.pageNum}页, 当前: ${this.pageNo}页`);
        this.$$("#mapfile-table").empty();
        for (let i = 0; i < metas.data.length; i++) {
            const item = metas.data[i], id = `mapfile-table-${i}`;
            const lookId = `mapfile-table-look${i}`;
            const updateId = `mapfile-table-update${i}`;
            const downloadId = `mapfile-table-download${i}`;
            const deleteId =`mapfile-table-delete${i}`;
            let tr= `
                <tr id="${id}">
                    <td class="label-cell" >${i + 1}</td>
                    <td class="label-cell">${item.name}</td>
                    <td class="label-cell">${code.Sign[item.sign].desc}</td>
                    <td class="label-cell">${code.MapType[item.type].desc}</td>
                    <td class="label-cell">${code.MapAssembly[item.piece].desc}</td>
                    <td class="label-cell">${item.major_ver + '_' + item.minor_ver}</td>
                    <td class="label-cell" style="width: 220px;">
                        <span style="color: var(--primary-color); cursor: pointer; margin-right: 8px;" id="${lookId}">查看</span>
                        <span style="color: var(--primary-color); cursor: pointer; margin-right: 8px;" id="${updateId}">更新</span>
                        <span style="color: var(--primary-color); cursor: pointer; margin-right: 8px;" id="${downloadId}">下载</span>
                        <span style="color: red; cursor: pointer;" id="${deleteId}">删除</span>
                    </td>
                </tr>
            `;
            this.$$("#mapfile-table").append(this.$$(tr));

            // 加载图纸
            this.$$(`#${lookId}`).on("click", async () => {
                this.popup.close();
                try {
                    this.app.dialog.preloader("正在获取矿图...");
                    const res = await this.api.getVector(item.meta_id);
                    if (res.code !== 0) {
                        this.toast(res.message);
                        this.app.dialog.close();
                        return;
                    }
                    const data = res.data;

                    // 初始化config信息
                    this.drawer.init(data.meta, data.layers);

                    // 将从网络上取下来的数据存入数据库
                    this.db.init(data).then(() => {
                        // 从本地提取数据
                        this.drawer.location().then(() => {
                            this.app.dialog.close();
                        })
                    })
                } catch(err) {
                    this.toast(err);
                    this.app.dialog.close();
                }
            })

            // 更新图纸meta
            this.$$(`#${updateId}`).on("click", async () => {
                this.update(item);
            })

            // 下载图纸
            this.$$(`#${downloadId}`).on("click", async () => {
                this.popup.close();
                try {
                    this.app.dialog.preloader("正在下载数据...");
                    await this.api.downloadDxf(item.meta_id, item.name);
                    this.app.dialog.close();
                } catch (err) {
                    this.toast(err)
                    this.app.dialog.close()
                }
            })

            // 删除图纸
            this.$$(`#${deleteId}`).on("click", async () => {
                this.popup.close();
                try {
                    this.app.dialog.preloader("正在删除数据...")
                    const res = await this.api.delMeta(item.meta_id);
                    if (res.code !== 0) {
                        this.toast(res.message);
                        this.app.dialog.close();
                        return;
                    }

                    // 删除数据中的meta_id的数据,并刷新本地数据
                    this.db.clear(item.meta_id).then(() => {
                        this.drawer.location().then(() => {
                            // 删除tree中的meta_id
                            const meta_ids = this.utils.getLocalStorage('meta_ids');
                            if (meta_ids !== null) {
                                const index = meta_ids.indexOf(item.meta_id);
                                if (index !== -1) {
                                    meta_ids.splice(index, 1);
                                    this.utils.setLocalStorage('meta_ids', meta_ids);
                                }
                            }

                            // 删除配置文件中的图层信息
                            const config = this.algo.getConfig();
                            if (config !== null) {
                                const layers = [];
                                for (const value of config.layers) {
                                    if (value.meta_id === item.meta_id) {
                                        const index2 = config.layer.indexOf(value.layer);
                                        if (index2 !== -1) {
                                            config.layer.splice(index2, 1);
                                        }
                                        continue;
                                    }
                                    layers.push(value);
                                }
                                config.layers = layers;
                                this.algo.setConfig(config);
                            }

                            this.getDataByPageNO().then(() => {
                                this.toast('删除数据成功。');
                                this.app.dialog.close();
                            });
                        });
                    });

                } catch (err) {
                    this.toast(err);
                    this.app.dialog.close();
                }
            })
        }
    }

    template() {
        const mapfile_popup_div = `
            <div class="popup mapfile-popup" style="width: 1200px; height: 600px;">
                <header>图件编辑</header>
                <article>
                    <div class="list inline-labels no-hairlines-md">
                        <div style="width: 100%; height: 48px;">
                            <div class="item-content item-input" style="width: 250px; float: left; margin-right: 15px;">
                                <div class="item-title item-label" style="width: 80px;">名称</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-name">
                                            <input type="text" id="mapfile-name">
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="item-content item-input" style="width: 250px; float: left; margin-right: 15px;">
                                <div class="item-inner">
                                    <div class="item-title item-label" style="width: 80px;">标志/煤层</div>
                                    <div class="item-input-wrap">
                                        <label for="mapfile-sign">
                                            <select id="mapfile-sign"></select>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="item-content item-input" style="width: 250px; float: left; margin-right: 15px;">
                                <div class="item-title item-label" style="width: 80px;">类型编码</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-type">
                                            <select id="mapfile-type"></select>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="item-content item-input" style="width: 250px; float: left; margin-right: 15px;">
                                <div class="item-title item-label" style="width: 80px;">图件编码</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-piece">
                                            <select id="mapfile-piece"></select>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <span class="icon iconfont" id="mapfile-search" style="font-size: var(--input-height)">
                                &#xe70f;
                            </span>
                        </ul>
                        </div>
                        <div class="card data-table" style="height: 450px;">
                            <table>
                                <thead>
                                    <tr">
                                        <th class="label-cell">#</th>
                                        <th class="label-cell">图件名称</th>
                                        <th class="label-cell">标志/煤层</th>
                                        <th class="label-cell">类型编码</th>
                                        <th class="label-cell">图件编码</th>
                                        <th class="label-cell">版本</th>
                                        <th class="label-cell" style="width: 200px;">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="mapfile-table"></tbody>
                            </table>
                        </div>
                    </div>
                </article>
                <footer>
                    <span id="mapfile-popup-prev" class="popup-page">
                        <<&nbsp;前一页&nbsp;&nbsp;&nbsp;&nbsp;
                    </span>
                    <span id="mapfile-table-page"></span>
                    <span id="mapfile-popup-next" class="popup-page">
                        &nbsp;&nbsp;&nbsp;&nbsp;后一页&nbsp;>>
                    </span>
                </footer>
                <a href="#" class="popup-closer" id="mapfile-popup-close"></a>
            </div>
            <div class="popup mapfile-popup-update" style="width: 460px; height: 390px;">
                <header>导入图档</header>
                <article>
                    <div class="list inline-labels no-hairlines-md">
                        <ul>
                            <li class="item-content item-input">
                                <div class="item-title item-label">图件名称</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-update-name">
                                            <input type="text" id="mapfile-update-name">
                                        </label>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">标志/煤层</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-update-sign">
                                            <select id="mapfile-update-sign" class="input-with-value"></select>
                                        </label>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">类型编码</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-update-type">
                                            <select id="mapfile-update-type" class="input-with-value"></select>
                                        </label>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">图件编码</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-update-piece">
                                            <select id="mapfile-update-piece" class="input-with-value"></select>
                                        </label>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">图件版本</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="mapfile-update-version">
                                            <select id="mapfile-update-version" class="input-with-value"></select>
                                        </label>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                </article>
                <footer>
                    <button class="button button-fill color-orange popup-close" 
                        id="mapfile-popup-update-submit">
                        确定
                    </button>
                    <button class="button button-fill color-gray popup-close"
                        id="mapfile-popup-update-cancel">
                        取消
                    </button>
                </footer>
            </div>
        `;
        this.$$('#app').append(mapfile_popup_div);
    }

    control() {
        this.$$("#mapfile-popup").on("click", async () => {
            this.$$(".mapfile-popup").css('left', this.utils.left(1200));
            this.popup = this.app.popup.create({ el: '.mapfile-popup' });
            this.popup.open();

            this.mine = this.utils.getLocalStorage('mine');
            if (this.mine === null) {
                this.toast("没有煤矿信息,请先选择煤矿。");
                this.popup.close();
                return;
            }

            this.search();
            this.page();
            await this.getDataByPageNO();
        })
    }
}